import { ref } from 'vue';
import md5 from 'md5';
import { forgetPassWord as ForgetPassWord } from '@/api/user/user';
import { Message, ValidatedError } from '@arco-design/web-vue';
import type { CallBackData } from '@/components/dialog/type.d';

export default function useAccount() {
    const dialogVisible = ref(false);

    const formRef = ref();

    const forgetForm = ref({
        mobile: '',
        shortCode: '',
        newPwd: '',
        againPassword: ''
    });

    // 忘记密码
    const handleUpdatePasswordClick = () => {
        dialogVisible.value = true;
    }

    // 弹窗按钮返回
    // 获取子组件点击按钮值
    const handleVisible = async (data: CallBackData) => {
        if (data.status === 'save') {
            const res = await formRef.value.validate();
            data.done(true);
            if (res !== undefined) {
                if (forgetForm.value.newPwd !== forgetForm.value.againPassword) {
                    formRef.value.setFields({
                        againPassword: {
                            status: 'error',
                            message: '确认新密码与新密码不同'
                        }
                    })
                }
            } else {
                if (forgetForm.value.newPwd !== forgetForm.value.againPassword) {
                    formRef.value.setFields({
                        againPassword: {
                            status: 'error',
                            message: '确认新密码与新密码不同'
                        }
                    })
                } else {
                    const { againPassword, ...newForgetForm } = forgetForm.value;
                    const res = await ForgetPassWord({
                        ...newForgetForm,
                        newPwd: md5(newForgetForm.newPwd),
                        shortCode: md5(newForgetForm.shortCode)
                    })
                    Message.success('修改成功');
                    formRef.value.resetFields();
                    dialogVisible.value = data.flag;
                }
            }
        } else if (data.status === 'clear') {
            formRef.value.resetFields();
            dialogVisible.value = data.flag;
        }
    }

    return {
        dialogVisible,
        formRef,
        forgetForm,
        handleUpdatePasswordClick,
        handleVisible
    }
}